package com.example.java_message_queue.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class MSGQueue {
    private String name;
    private boolean durable;
    private boolean exclusive;  // 是否是被一个 Consumer 独占
    private boolean autoDelete;
    private Map<String, Object> arguments = new HashMap<>();

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public Object getArgument(String key) {
        return arguments.get(key);
    }

    public void setArguments(String value) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            arguments = objectMapper.readValue(value, new TypeReference<HashMap<String, Object>>() { });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }


    ////////////////////////////////////////////////////////////////////////////////////
    // 下列逻辑用来支撑消费消息功能
    ////////////////////////////////////////////////////////////////////////////////////

    // 该队列被哪些消费者订阅
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    // 轮询序号
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }

    public ConsumerEnv chooseConsumer() {
        if (consumerEnvList.size() == 0) {
            return null;
        }
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }

}
